package com.mj.coupon.util;

import android.annotation.SuppressLint;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

@SuppressLint("SimpleDateFormat")
public class DateUtils {
	public static String defaultDatePattern = "yyyy-MM-dd";
	public static String datePattern = "yyyy-MM-dd HH:mm:ss";
	public static String timePattern = "HH:mm";
	
	public static DateFormat EntelSMSTimeFormat = new SimpleDateFormat("yyyyMMddHHmmss");

	public static String getDatePattern() {

		return defaultDatePattern;
	}

	/**
	 * This method attempts to convert an Oracle-formatted date in the form
	 * dd-MMM-yyyy to mm/dd/yyyy.
	 * 
	 * @param aDate
	 *            date from database as a string
	 * @return formatted string for the ui
	 */
	public static final String getDate(Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate != null) {
			df = new SimpleDateFormat(getDatePattern());
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}

	/**
	 * This method generates a string representation of a date/time in the
	 * format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param strDate
	 *            a string representation of a date
	 * @return a converted Date object
	 * @see java.text.SimpleDateFormat
	 * @throws ParseException
	 */
	public static final Date convertStringToDate(String aMask, String strDate)
			throws ParseException {
		SimpleDateFormat df = null;
		Date date = null;
		df = new SimpleDateFormat(aMask);
		
		try {
			date = df.parse(strDate);
		} catch (ParseException pe) {
			// log.error("ParseException: " + pe);
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());
		}

		return (date);
	}

	/**
	 * 
	 * @param date
	 * @return
	 */
	public static final java.sql.Date convertUtilDateToSqlDate(
			java.util.Date date) {
		java.sql.Date current = new java.sql.Date(date.getTime());
		return current;

	}

	/**
	 * This method returns the current date time in the format: MM/dd/yyyy HH:MM
	 * a
	 * 
	 * @param theTime
	 *            the current time
	 * @return the current date/time
	 */
	public static String getTimeNow(Date theTime) {
		return getDateTime(timePattern, theTime);
	}

	/**
	 * This method returns the current date in the format: MM/dd/yyyy
	 * 
	 * @return the current date
	 * @throws ParseException
	 */
	public static Calendar getToday() throws ParseException {
		Date today = new Date();
		SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

		// This seems like quite a hack (date -> string -> date),
		// but it works ;-)
		String todayAsString = df.format(today);
		Calendar cal = new GregorianCalendar();
		cal.setTime(convertStringToDate(todayAsString));

		return cal;
	}

	/**
	 * This method generates a string representation of a date's date/time in
	 * the format you specify on input
	 * 
	 * @param aMask
	 *            the date pattern the string is in
	 * @param aDate
	 *            a date object
	 * @return a formatted string representation of the date
	 * 
	 * @see java.text.SimpleDateFormat
	 */
	public static final String getDateTime(String aMask, Date aDate) {
		SimpleDateFormat df = null;
		String returnValue = "";

		if (aDate == null) {
			
		} else {
			df = new SimpleDateFormat(aMask);
			returnValue = df.format(aDate);
		}

		return (returnValue);
	}
	
	
	public static final String getGMTDate(Date aDate) {
		mFormatRfc822_e.setTimeZone(TimeZone.getTimeZone("GMT")); 
		return mFormatRfc822_e.format(aDate);
	}
	
	public static final String getRfc822Date(Date aDate) {
		return mFormatRfc822.format(aDate);
	}

	/**
	 * This method generates a string representation of a date based on the
	 * System Property 'dateFormat' in the format you specify on input
	 * 
	 * @param aDate
	 *            A date to convert
	 * @return a string representation of the date
	 */
	public static final String convertDateToString(Date aDate) {
		return getDateTime(getDatePattern(), aDate);
	}

	/**
	 * This method converts a String to a date using the datePattern
	 * 
	 * @param strDate
	 *            the date to convert (in format yyyy-mm-dd)
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static Date convertStringToDate(String strDate)
			throws ParseException {
		Date aDate = null;

		try {
			
			aDate = convertStringToDate(getDatePattern(), strDate);
		} catch (ParseException pe) {
			
			pe.printStackTrace();
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());

		}

		return aDate;
	}
	
	
	/**
	 * This method converts a String to a date using the datePattern
	 * 
	 * @param strDate
	 *            the date to convert (in format yyyy-mm-dd)
	 * @return a date object
	 * 
	 * @throws ParseException
	 */
	public static Date convertStringToDateByPattern(String strDate)
			throws ParseException {
		Date aDate = null;

		try {
			
			aDate = convertStringToDate(getDatePattern(), strDate);
		} catch (ParseException pe) {
			
			pe.printStackTrace();
			throw new ParseException(pe.getMessage(), pe.getErrorOffset());

		}

		return aDate;
	}


	private static final SimpleDateFormat mFormat8chars = new SimpleDateFormat(
			"yyyyMMdd");

	private static final SimpleDateFormat mFormatIso8601Day = new SimpleDateFormat(
			"yyyy-MM-dd");

	private static final SimpleDateFormat mFormatZh = new SimpleDateFormat(
			"yyyy年MM月dd日");

	private static final SimpleDateFormat mFormatIso8601 = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ssZ");

	//星期一, 2 八月 2010 10:41:31 CST
	private static final SimpleDateFormat mFormatRfc822 = new SimpleDateFormat(
			"EEE, d MMM yyyy HH:mm:ss z");
	
	//Mon, 2 Aug 2010 10:41:05 CST
	private static final SimpleDateFormat mFormatRfc822_e = new SimpleDateFormat(
			"EEE, d MMM yyyy HH:mm:ss z",Locale.ENGLISH);

	//mFormatRfc822.setTimeZone(TimeZone.getTimeZone("GMT")); 


	private static final SimpleDateFormat mFormatY2S = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	/**
	 * Returns a string the represents the passed-in date parsed according to
	 * the passed-in format. Returns an empty string if the date or the format
	 * is null.
	 */
	public static String format(Date aDate, SimpleDateFormat aFormat) {
		if (aDate == null || aFormat == null) {
			return "";
		}
		return aFormat.format(aDate);
	}
	
	public static String format(Date aDate, String aFormat) {
		if (aDate == null || aFormat == null) {
			return "";
		}
		return  new SimpleDateFormat(aFormat).format(aDate);
	}

	public static String getDefaultDateFormat(Date aDate) {

		return DateUtils.format(aDate, mFormatIso8601Day);
	}
	
	public static String getTimeFormat(Date aDate) {

		return DateUtils.format(aDate, mFormatIso8601);
	}
	
	public static String getCurrentDateFormat8() {
		return DateUtils.format(new Date(), mFormat8chars);
	}
	
	public static String getCurrentDateY2S() {
		return DateUtils.format(new Date(), mFormatY2S);
	}

	/**
	 * 获取中文格式的日期格式2005年09月03日
	 * 
	 * @param data
	 * @return
	 */
	public static String getZhTimeFormat(Date data) {

		return DateUtils.format(data, mFormatZh);

	}

	public static String getDefaultDateFormat(long aDate) {
		Date date = new Date();
		date.setTime(aDate);

		return DateUtils.format(date, mFormatIso8601Day);
	}

	/**
	 * ouyangli 2005-09-07 按照需要获得符合"number值"日后的日期
	 * 
	 * @param number
	 * @return
	 */
	public static String getDateofneed(int number) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date myDate = new java.util.Date();
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * number;
		myDate.setTime(myTime * 1000);
		String needDate = formatter.format(myDate);
		return needDate;
	}

	public static String getYear(Date date) {
		String currentTime = DateUtils.getDefaultDateFormat(date.getTime());
		String year = currentTime.substring(0, 4);
		// String month = currentTime.substring(5, 7);
		return year;

	}

	public static String getMonth(Date date) {
		String currentTime = DateUtils.getDefaultDateFormat(date.getTime());
		// String year = currentTime.substring(0, 4);
		String month = currentTime.substring(5, 7);
		return month;

	}

	public static String getDay(Date date) {
		String currentTime = DateUtils.getDefaultDateFormat(date.getTime());
		// String year = currentTime.substring(0, 4);
		// String month = currentTime.substring(5, 7);

		String day = currentTime.substring(8, 10);
		return day;

	}
	
	/**
	 * 根据日期生成附件上传目录结构
	 * \\2004\\09
	 * @param date
	 * @return
	 */
	public static String getDirectoryByDate(Date date){
		return getYear(date)+File.separator+getMonth(date)+File.separator;
		
		
	}
	/**
	 * 根据日期获取访问url（相对于路径）
	 * @param date
	 * @return
	 */
	public static String getUrlByDate(Date date){
		return getYear(date)+"/"+getMonth(date)+"/";
		
		
	}

	
	/**
	   * 给date添加(days,hours,minutes , seconds)时间偏移
	   * @param date		//时间基准
	   * @param days		//偏移的天数
	   * @param hours		//偏移的小时
	   * @param minutes		//偏移的分钟
	   * @param seconds		//偏移的秒数
	   * @return Date		//返回偏移后的日期
	   * @author tzc 2005-09-21 )
	   */
	  public static synchronized Date Add(Date date , int days , int hours , int minutes , int seconds) {

	      Date dt = date;
	      if(dt != null)
	      {
	      	Calendar calendar = Calendar.getInstance(); 
	      	calendar.setTime(dt); 
	    
			if(days != 0)
			{
			    calendar.add(Calendar.DATE,days);	
			}
			if(hours != 0)
			{
			    calendar.add(Calendar.HOUR ,hours);	
			}
			if(minutes != 0)
			{
			    calendar.add(Calendar.MINUTE ,minutes);	
			}
			if(seconds != 0)
			{
			    calendar.add(Calendar.SECOND ,seconds);	
			}
			dt = calendar.getTime() ;
	      }
	      return dt;
	  }
	  
	  
	  /**
	   * 获取当前年
	   * @return
	   */
	  public static int getCurrentYear(){
		  Calendar calendar = Calendar.getInstance(); 
		  return calendar.get(Calendar.YEAR);
		  
	  }
	  
	  /**
	   * 取得判断日期是否是星期二或者星期五,如果不是则取的下一个星期二星期五的日期
	   * @param date //需要判断的日期
	   * @return Date	//返回判断结果的日期
	   * @author tzc 2006-01-24
	   */
	  public static Date getNextTuesDayOrFriday( Date date ){
		  if( date != null ){
			  do{
				  date = Add(date,1,0,0,0 );
			  }
			  while( date.getDay() != 2 && date.getDay() != 5 );
		  }
		  
		  return date;
	  }

	public static String getTimePattern() {
		return timePattern;
	}
	
	public static Long getMillisByDate(String date)
	{
		Calendar   nowTime   =   new   GregorianCalendar(); 
		DateFormat format = DateFormat.getDateInstance();
		Date temp2 = null;
		try {
			temp2 = format.parse(date);
		} catch (ParseException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		nowTime.setTime(temp2);
		return nowTime.getTimeInMillis();
	}
	
	public static Long getMillisByDate(Date date)
	{
		Calendar   nowTime   =   new   GregorianCalendar(); 
		
		nowTime.setTime(date);
		return nowTime.getTimeInMillis();
	}
	
//	获取指定时间小时数
	public static String getHourByDate(Date date)
	{
		return getTimeNow(date).substring(0,2);
	}
//	查看今天是本年第几周
	public static int  getThisWeek()  throws  Exception     
	{   
        try{   
            java.util.Calendar   calendar   =   new   java.util.GregorianCalendar();   
            int   thisWeek   =   calendar.get(Calendar.WEEK_OF_YEAR);   
            return   thisWeek;   
            }   
          catch(Exception   e)   {   
            throw   new   Exception   (e.toString());   
        }   
    }
	
	//取前一天的日期
	public static Date getYesterdayCurrentDate()
	{
		long millis = System.currentTimeMillis();
		millis = millis - 24*60*60*1000;
		Date date = new Date(millis);
		return date;
	}
	
	public static String handle(String date) {
		String result = "";
		
		if(date == null || date.equals(""))
			return result;
		
		int pos = date.indexOf(" ");
		if(pos < 0)
			return date;
		else
			result = date.substring(0, pos);
		
		return result;
	}

    public static synchronized String formatEntelSMSDate(Date date) {
    	if(date == null)
    		date = new Date();
        return EntelSMSTimeFormat.format(date);
    }
    public static synchronized String formatEntelSMSDate(String strdate) {
    	if(strdate == null || strdate.equals("")){
    		return EntelSMSTimeFormat.format(new Date());
    	}else{
    		return EntelSMSTimeFormat.format(strdate);
    	}        
    }
	
  	//获取几天之前时间
  	public static String getAnyDayAgo(int x) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		ca.setTime(new Date());
		ca.add(Calendar.DAY_OF_YEAR, x);
		Date date2 = ca.getTime();
		String yesterday = format.format(date2);
		return yesterday;
	}
  	
  	public static void main(String[] args){
  		System.out.println(DateUtils.getAnyDayAgo(0));
  	}
}
